package com.ict.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.api.dto.IctSkuStockDTO;
import com.ict.api.entity.IctSkuStock;
import com.ict.api.result.ApiResponse;
import com.ict.api.vo.IctSkuStockVO;
import com.ict.commons.constants.IctConstants;
import com.ict.mapper.IctSkuStockMapper;
import com.ict.service.IctSkuStockService;
import com.ict.util.GeneratorCode;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * sku的库存 服务实现类
 * </p>
 *
 * @author wjp
 * @since 2025-03-23
 */
@Service
public class IctSkuStockServiceImpl extends ServiceImpl<IctSkuStockMapper, IctSkuStock> implements IctSkuStockService {

    @Resource
    private IctSkuStockMapper stockMapper;

    @Override
    public List<IctSkuStockVO> getStockInfo(IctSkuStockDTO skuStockDTO) {
        LambdaQueryWrapper<IctSkuStock> queryWrapper = new LambdaQueryWrapper<>();


        queryWrapper.eq(skuStockDTO.getProductId() != null, IctSkuStock::getProductId, skuStockDTO.getProductId());
        queryWrapper.eq(skuStockDTO.getSkuCode() != null, IctSkuStock::getSkuCode, skuStockDTO.getSkuCode());

        List<IctSkuStock> ictSkuStockList = stockMapper.selectList(queryWrapper);
        List<IctSkuStockVO> list = new ArrayList<>();
        for (IctSkuStock ictSkuStock : ictSkuStockList) {
            IctSkuStockVO ictSkuStockVO = new IctSkuStockVO();
            BeanUtils.copyProperties(ictSkuStock, ictSkuStockVO);
            list.add(ictSkuStockVO);
        }

        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse<String> deductStock(IctSkuStockDTO stockDeductDTO) {
        // 扣减库存时确保库存足够
        LambdaUpdateWrapper<IctSkuStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .setSql("stock = stock - " + stockDeductDTO.getQuantity()) // 直接 SQL 扣减
                .eq(IctSkuStock::getSkuCode, stockDeductDTO.getSkuCode())
                .ge(IctSkuStock::getStock, stockDeductDTO.getQuantity()); // 只在库存足够时更新

        int updated = stockMapper.update(null, updateWrapper);

        if (updated > 0) {
            return ApiResponse.success("库存扣减成功");
        } else {
            return ApiResponse.error("库存不足，扣减失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse<String> addStock(IctSkuStockDTO stockAddDTO) {
        LambdaUpdateWrapper<IctSkuStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .setSql("stock = stock + " + stockAddDTO.getQuantity()) // 直接 SQL 方式增加库存
                .eq(IctSkuStock::getSkuCode, stockAddDTO.getSkuCode());

        int updated = stockMapper.update(null, updateWrapper);

        if (updated > 0) {
            return ApiResponse.success("库存增加成功");
        } else {
            return ApiResponse.error("库存增加失败，商品不存在");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse<String> lockStock(IctSkuStockDTO stockLockDTO) {
        LambdaUpdateWrapper<IctSkuStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .setSql("stock = stock - " + stockLockDTO.getQuantity() + ", lock_stock = lock_stock + " + stockLockDTO.getQuantity()) // 直接 SQL 操作库存
                .eq(IctSkuStock::getSkuCode, stockLockDTO.getSkuCode())
                .ge(IctSkuStock::getStock, stockLockDTO.getQuantity()); // 确保库存足够

        int updated = stockMapper.update(null, updateWrapper);

        if (updated > 0) {
            return ApiResponse.success("库存锁定成功");
        } else {
            return ApiResponse.error("库存不足，锁定失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse<String> unlockStock(IctSkuStockDTO stockUnlockDTO) {
        LambdaUpdateWrapper<IctSkuStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .setSql("stock = stock + " + stockUnlockDTO.getQuantity() +
                        ", lock_stock = lock_stock - " + stockUnlockDTO.getQuantity())
                .eq(IctSkuStock::getSkuCode, stockUnlockDTO.getSkuCode())
                .ge(IctSkuStock::getLockStock, stockUnlockDTO.getQuantity()); // 确保锁定库存足够

        int updated = stockMapper.update(null, updateWrapper);

        if (updated > 0) {
            return ApiResponse.success("库存释放成功");
        } else {
            return ApiResponse.error("释放失败，锁定库存不足");
        }
    }

    @Override
    public ApiResponse<String> addStockInfo(IctSkuStockDTO stockAddDTO) {
        LambdaQueryWrapper<IctSkuStock> lqw = new LambdaQueryWrapper<>();
        lqw.eq(IctSkuStock::getProductId, stockAddDTO.getProductId());
        Integer integer = stockMapper.selectCount(lqw);
        if (integer > 0) {
            return ApiResponse.error("库存信息已存在，不可重复添加库存");
        }
        stockAddDTO.setSkuCode(GeneratorCode.generateWithPrefix(IctConstants.SKU_PREFIX));
        stockMapper.insert(stockAddDTO);
        return ApiResponse.success("库存添加成功");
    }
}
